from flask import session
from flask_restful import Resource

from database import Database


# Mock user database
class getOrders(Resource):
    def get(self):
        db = Database()
        user_id = session.get('username')
        if user_id is None:
            return {'message': 'You are not logged in!'}, 401
        else:

            orders = db.execute_query("SELECT * FROM `order` WHERE userId = %s", (user_id,))
            if orders:
                orders_formatted = []
                for order in orders:
                    print(order[0])
                    lineBooks = db.execute_query("SELECT * FROM linebook WHERE orderId = %s", (order[0],))

                    listBooks_json = []
                    if lineBooks:
                        print(1)
                        for linebook in lineBooks:
                            print(linebook[0])
                            book = db.execute_query("SELECT * FROM book WHERE bookId = %s", (linebook[3],))  # Fix here

                            book_data = {
                                "bookId": book[0],
                                "categoryId": book[1],
                                "imageUrl": book[2],
                                "stackId": book[3],
                                "ownerId": book[4],
                                "condition": book[5],

                                "fee": str(book[6]),
                                "price": str(book[7]),
                                "status": book[8],
                                "LineBookStatus": linebook[2],
                                "libraryAddress": linebook[4],
                                "borrowedTill": str(linebook[5]),
                                "returnAfter": str(linebook[6]),
                                "dayToken": str(linebook[7])
                            }
                            listBooks_json.append(book_data)
                    order_data = {
                        "orderId": order[0],
                        "userId": order[1],
                        "dateCreated": order[2].strftime("%Y-%m-%d %H:%M:%S"),
                        "status": order[3],
                        "quantity": order[4],
                        "class": order[5],
                        "listBooks": listBooks_json  # Changed to listBooks
                    }
                    orders_formatted.append(order_data)
                return {"orders": orders_formatted}, 200
            else:
                return {"message": "No orders found"}, 404
